package com.gxuwz.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

/**
 * 重定向策略
 * <p>功能描述：使security框架可以实现转发功能，(默认是重定向)
 * @author Timo
 * @date:2018年5月20日
 */
public class MyRedirectStrategy implements RedirectStrategy{
	
	protected final Log logger = LogFactory.getLog(getClass());
	private final Logger log = Logger.getLogger(getClass());

	private boolean contextRelative;

	@Override
	public void sendRedirect(HttpServletRequest request,
			HttpServletResponse response, String url) throws IOException {
		String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
		log.info("重定向策略  url: "+url+"   redirectUrl: "+redirectUrl);
		redirectUrl = response.encodeRedirectURL(url);

		if (logger.isDebugEnabled()) {
			logger.debug("Redirecting to '" + redirectUrl + "'");
		}
		try {
			request.getRequestDispatcher(redirectUrl).forward(request, response);
		} catch (ServletException e) {
			System.out.println( "security转发失败！" );
			e.printStackTrace();
		}
	}
	
	private String calculateRedirectUrl(String contextPath, String url) {
		if (!UrlUtils.isAbsoluteUrl(url)) {
			if (contextRelative) {
				return url;
			}
			else {
				return contextPath + url;
			}
		}

		// Full URL, including http(s)://

		if (!contextRelative) {
			return url;
		}

		// Calculate the relative URL from the fully qualified URL, minus the last
		// occurrence of the scheme and base context.
		url = url.substring(url.lastIndexOf("://") + 3); // strip off scheme
		url = url.substring(url.indexOf(contextPath) + contextPath.length());

		if (url.length() > 1 && url.charAt(0) == '/') {
			url = url.substring(1);
		}

		return url;
	}

	/**
	 * If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol
	 * and context path (defaults to <tt>false</tt>).
	 */
	public void setContextRelative(boolean useRelativeContext) {
		this.contextRelative = useRelativeContext;
	}

}
